// SocketUtil.js
import { getToken } from '@/utils/auth'

class SocketUtil {
  /**
   * 连接指定socket
   * @param socketUrl socket 接口
   * @param onMessageCallback 回调
   * @returns {WebSocket} socket实例
   */
  static connect(socketUrl, onMessageCallback) {
    const socket = new WebSocket(`ws://127.0.0.1:8080${socketUrl}?Authorization=${getToken()}`);

    socket.onopen = () => {
      console.log('WebSocket connection opened');
    };

    socket.onmessage = (event) => {
      const data = JSON.parse(event.data).data;
      if (onMessageCallback) {
        onMessageCallback(data);
      }
    };

    socket.onerror = (error) => {
      console.error('Socket error:', error);
    };

    socket.onclose = () => {
      console.log('Socket close');
    };

    return socket;
  }

  static disconnect(socket) {
    if (socket) {
      socket.close();
    }
  }
}

export default SocketUtil;
